<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\user\model;

use think\Model;
use think\facade\Db;

/**
 * 会员用户模型
 * @package app\admin\model
 */
class Member extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'user_member';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
	
	// 错误信息
	protected $error;
	
	// 用户信息
	protected $user;
	
    // 获取注册ip
    public function setSignupIpAttr()
    {
        return get_client_ip(1);
    }
	
	// 关联模型
	public function profile()
	{
		return $this->hasOne(Vip::class, 'member_id');
	}
    /**
     * 自动登录
     * @param bool $rememberme 是否记住登录，默认7天
     * @author PaulXun <paulxun@qq.com>
     * @return bool|int
     */
    public function autoLogin($uid = 0)
    {	
		if($uid === 0){
			$user = $this->user;
		}else{
			$user = self::where('id', $uid)->find();
		}
		if ($user->status != 1) {
			$this->error = '用户不存在或被禁用';
			return false;
		}
        // 记录登录SESSION和COOKIES
        $auth = [
            'uid'             => $user->id,
            'group'           => $user->group,
			'openid'          => $user->openid,
            'role'            => $user->role,
            'role_name'       => self::role($user->role),
            'avatar'          => $user->avatar_img,
            'nickname'        => $user->nickname,
            'last_login_time' => $user->last_login_time,
            'last_login_ip'   => get_client_ip(1),
        ];
        session('member_auth', $auth);
        session('member_auth_sign', data_auth_sign($auth));
		
		// 更新登录信息
		$user->last_login_time =  $auth['last_login_time'];
		$user->last_login_ip   =  $auth['last_login_ip'];
		$user->save();

        // 记住登录
        $signin_token = $user->nickname.$user->id.$user->last_login_time;
        cookie('member_id', $user->id, 24 * 3600 * 7);
        cookie('member_signin_token', data_auth_sign($signin_token), 24 * 3600 * 7);
		
        return $user->id;
    }
	
	/* 保存用户信息
	 * @param array $data 用户资料
	 * @return bool|int 
	 */
	public function saveData($data, $login = true)
	{
		if (cookie('reging')) {
			$this->error = '请勿连续登陆';
			return false;
		}
		$time = time(); // 当前时间戳
		cookie('reging', 1, 5);
		if (isset($data['unionid']) && $data['unionid'] != ''){
			$user = self::where('unionid', '=', $data['unionid'])->find();
		}else{
			$user = self::where('openid', '=', $data['openid'])->find();
		}
		if (!$user) {
			$data['status'] = 1;
			$data['password'] = md5($data['key']);
			$data['save_time'] = $time;
			$data['last_login_time'] = $time;
			$data['last_login_ip']   = get_client_ip(1);
			$user = self::create($data);
			$this->user = $user;
			if(!$user){
				$this->error = '新增基础信息出错';
				return false;
		    }
		}else{
			$this->user = $user;
			// 超过24小时未更新
			if ($user['save_time'] + 3600 * 24 < $time){
				$user->save_time = $time;
				$user->avatar_img = $data['avatar_img'];
				$user->nickname = $data['nickname'];
				if(true !== $user->save()){
					$this->error = '更新基础信息出错';
					return false;
				}
			}
			if (isset($data['openid']) && $user['openid'] == ''){
				$user->openid = $data['openid'];
				$user->save();
			}
			if (isset($data['wxapp_openid']) && $user['wxapp_openid'] == ''){
				$user->wxapp_openid = $data['wxapp_openid'];
				$user->save();
			}
		}
		if ($login == false) return $user->id;
		return $this->autoLogin();
	}
	
	/**
	 * 获取所有后代id
	 * @param int $pid 父级id
	 * @author PaulXun <paulxun@qq.com>
	 * @return array
	 */
	public static function getChildsId($pid = 0)
	{
	    $ids = self::where('pid', $pid)->column('id');
	    foreach ($ids as $value) {
	        $ids = array_merge($ids, self::getChildsId($value));
	    }
	    return $ids;
	}
	
	/**
	 * 客户端类型
	 * @param int $id 类型id
	 * @author paulxun
	 * @return array|static
	 */
	public static function role($id = 99)
	{
		$types = [
			'wechat' => '微信公众号',
			'ali' 	 => '支付宝',
			'wxapp'  => '微信小程序',
		];
	    if ($id === 99) {
	        $result = $types;
	    }else{
			$result = '';
			if(isset($types[$id])) $result = $types[$id];
		}
	    return $result;
	}
	/* 获取支行人员列表
	 * @return array|mixed
	 */
	public static function getList()
	{
		$data_list = self::where('branch_bind', 1)->column('realname', 'id');
	    return $data_list;
	}
	/* 获取相关人员列表
	 * @return array|mixed
	 */
	public static function getAbout($id = 0)
	{
	    $info = Db::name('bank_service')->where('id', $id)->find();
	    if(!$info) return null;
		$data_list = self::where('id', $info['uid'])->whereOr('mobile', $info['mobile'])->whereOr('realname', $info['name'])->column('nickname', 'id');
	    return $data_list;
	}
	
	/* 获取openid
	 * @return array|mixed
	 */
	public static function getOpenid($id = 0)
	{
		$openid = cache('openid_'.$id);
		if (!$openid) {
			$openid = self::where('id', $id)->value('openid');
			if (!$openid) return false;
			cache('openid_'.$id, $openid);
		}
	    return $openid;
	}
	
	/**
	 * 获取错误信息
	 * @access public
	 * @return mixed
	 */
	public function getError()
	{
	    return $this->error;
	}
	
	/**
	 * 数据更新事件
	 * @access public
	 * @return mixed
	 */
	public static function onBeforeUpdate($member)
	{
		if (!empty($member->auth)) {
			$user = self::find($member->id);
			if ($user['auth'] != $member->auth && $member->auth == 1) {
				// 执行认证的时候查找VIP信息
				$vipModel = new \app\user\model\Vip;
				$vip = $vipModel->where('member_id', '=', $user['id'])->find();
				if (!$vip) {
					$vipModel->member_id = $member->id;
					$vipModel->pid = $user['pid'];
					$vipModel->realname = $user['realname'];
					$vipModel->mobile = $user['mobile'];
					$vipModel->idcard = $user['idcard'];
					$vipModel->save();
				} else {
					$vip->pid = $user['pid'];
					$vip->realname = $user['realname'];
					$vip->mobile = $user['mobile'];
					$vip->idcard = $user['idcard'];
					$vip->save();
				}
			}
		}
	}
}
